package net.sf.midollo.utils;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.CommConnection;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Display;

public class MidpUtils {

  public static final String UPPERCASE_LATIN = "MIDP_UPPERCASE_LATIN";
  public static final String LOWERCASE_LATIN = "MIDP_LOWERCASE_LATIN";

  public static OutputStream LOG_STREAM = null;

  public static void log(String msg) throws IOException {
    if (LOG_STREAM != null) {
      msg += '\n';
      synchronized (MidpUtils.class) {
        LOG_STREAM.write(msg.getBytes());
        LOG_STREAM.flush();
      }
    }
  }

  public static void showError(Display display, Exception ex) {
    ex.printStackTrace();
    display.setCurrent(new Alert("Error", ex.toString(), null, AlertType.ERROR), display.getCurrent());
  }

  public static void showInfo(Display display, String msg) {
    display.setCurrent(new Alert("Info", msg, null, AlertType.INFO), display.getCurrent());
  }

  public static String getString(ChoiceGroup choiceGroup) {
    int idx = choiceGroup.getSelectedIndex();
    if (idx < 0)
      return null;
    return choiceGroup.getString(idx);
  }

  public static String getCommUri(String port, String params) {
    String uri = "comm:";
    if (port != null)
      uri += port;
    if (params != null) {
      params = params.trim();
      if (params.length() > 0)
        uri += ';' + params;
    }
    return uri;
  }

  public static String getSocketUri(String host, int port) {
    String uri = "socket://";
    if (host != null) {
      host = host.trim();
      if (host.length() > 0)
        uri += host;
    }
    if (port >= 0)
      uri += ':' + port;
    return uri;
  }

  public static String getSocketConnectionId(SocketConnection sc) throws IOException {
    return sc.getLocalAddress() + ':' + sc.getLocalPort() + '-' + sc.getAddress() + ':' + sc.getPort();
  }

  public static String getServerSocketConnectionId(ServerSocketConnection sc) throws IOException {
    return sc.getLocalAddress() + ':' + sc.getLocalPort();
  }

  public static String getSocketOptions(SocketConnection sc) throws IOException {
    return "D=" + sc.getSocketOption(SocketConnection.DELAY) //
        + ";KA=" + sc.getSocketOption(SocketConnection.KEEPALIVE) //
        + ";L=" + sc.getSocketOption(SocketConnection.LINGER) //
        + ";RB=" + sc.getSocketOption(SocketConnection.RCVBUF) //
        + ";SB=" + sc.getSocketOption(SocketConnection.SNDBUF);
  }

  public static String getCommOptions(CommConnection cc) throws IOException {
    return "BR=" + cc.getBaudRate();
  }
}
